import torch
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

xy = np.loadtxt("./data/diabetes.csv.gz", delimiter=",", dtype=np.float32)
# print(xy)
x_data = torch.from_numpy(xy[:, :-1])
y_data = torch.from_numpy(xy[:, [-1]])

class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear1 = torch.nn.Linear(8, 6)
        self.linear2 = torch.nn.Linear(6, 4)
        self.linear3 = torch.nn.Linear(4, 1)
        self.activate = torch.nn.ReLU()
        self.sigmoid = torch.nn.Sigmoid() # 需要先将 Sigmoid 类进行实例化，才能在后续调用中使用该激活函数

    def forward(self, x):
        x = self.activate(self.linear1(x))
        x = self.activate(self.linear2(x))
        x = self.sigmoid(self.linear3(x))
        return x

model = Model()
criterion = torch.nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr = 0.01)

loss_list = []
epoch_list = []

for epoch in range(200):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    print(epoch, loss.item())
    loss_list.append(loss.item())
    epoch_list.append(epoch)

    optimizer.zero_grad()
    loss.backward()

    optimizer.step()

matplotlib.use("TkAgg")
plt.plot(epoch_list, loss_list)
plt.xlabel("epoch")
plt.ylabel("loss")
plt.show()

